package com.zygh.lz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.zygh.lz.dao.InformationMapper;
import com.zygh.lz.dao.InformationUserMapper;
import com.zygh.lz.entity.Information;
import com.zygh.lz.entity.InformationUser;
import com.zygh.lz.entity.Staff;
import com.zygh.lz.entity.bean.Pushsource;
import com.zygh.lz.entity.vo.CoordinateData;
import com.zygh.lz.service.InformationService;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.vo.ResultBean;
import com.zygh.lz.vo.ResultBeans;
import io.swagger.models.auth.In;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class InformationServiceImpl implements InformationService {

    @Resource
    private InformationMapper informationMapper;
    @Resource
    private InformationUserMapper informationUserMapper;


    /**
     * 查询所有记录
     *
     * @return 返回集合，没有返回空List
     */
    @Override
    public List<Information> listAll() {
        return informationMapper.listAll();
    }

    @Override
    public ResultBeans findInformationByType(String acceptWarningSignal, String isRead) {
        List<Information> informationByType = informationMapper.findInformationByType(acceptWarningSignal, isRead);
        return ResultUtil.resultBeansSuccess(informationByType);
    }


    /**
     * 根据主键查询
     *
     * @param id 主键
     * @return 返回记录，没有返回null
     */
    @Override
    public Information getById(Integer id) {
        return informationMapper.getById(id);
    }

    /**
     * 新增，插入所有字段
     *
     * @param information 新增的记录
     * @return 返回影响行数
     */
    @Override
    public int insert(Information information) {
        return informationMapper.insert(information);
    }

    /**
     * 新增，忽略null字段
     *
     * @param information 新增的记录
     * @return 返回影响行数
     */
    @Override
    public int insertIgnoreNull(Information information) {
        return informationMapper.insertIgnoreNull(information);
    }

    /**
     * 修改，修改所有字段
     *
     * @param information 修改的记录
     * @return 返回影响行数
     */
    @Override
    public int update(Information information) {
        return informationMapper.update(information);
    }

    /**
     * 修改，忽略null字段
     *
     * @param information 修改的记录
     * @return 返回影响行数
     */
    @Override
    public ResultBeans updateIgnoreNull(Information information) {
        return ResultUtil.resultBeansexecOp(informationMapper.updateIgnoreNull(information), "修改");
    }

    /**
     * 删除记录
     *
     * @param information 待删除的记录
     * @return 返回影响行数
     */
    @Override
    public int delete(Information information) {
        return informationMapper.delete(information);
    }


    @Override
    public ResultBean findPushHistory(Pushsource pushsource) {
        DecimalFormat df = new DecimalFormat("#.0");
        PageHelper.startPage(pushsource.getPageNum(), pushsource.getPageSize());
        List<Information> pushHistory = informationMapper.findPushHistory(pushsource);
        //接受率
        for (Information information : pushHistory) {
            //已读
            List<InformationUser> inforUserReadById = informationUserMapper.findInforUserReadById(information.getId(), 1);
            //发送消息所有接收人
            List<InformationUser> inforUserById = informationUserMapper.findInforUserById(information.getId());
            information.setAcceptName(inforUserById);
            double readRate = 0;
            if (inforUserById.size() == 0 || inforUserReadById.size() == 0) {
                information.setReadRate(readRate);
            } else {
                readRate = Double.valueOf(df.format((float) inforUserReadById.size() / inforUserById.size()));
                information.setReadRate(readRate);
            }
        }
        PageInfo<Information> pageInfo = new PageInfo<>(pushHistory);
        return ResultUtil.setOK("success", pageInfo);
    }

    @Override
    public String exportMessage(HttpServletResponse response, Pushsource pushsource) throws IOException {
        DecimalFormat df = new DecimalFormat("#");
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 设置只导出有别名的字段
        writer.setOnlyAlias(true);
        pushsource.setPageNum(1);
        pushsource.setPageSize(100000000);
        ResultBean pushHistory = this.findPushHistory(pushsource);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(pushHistory.getData()));
        List<Information> list = new Gson().fromJson(jsonObject.getJSONArray("list").toString(), new TypeToken<List<Information>>() {
        }.getType());

        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
        System.out.println("list:" + list);
        for (Information listInfo : list) {
            Map<String, Object> row1 = new LinkedHashMap<>();
            row1.put("发送人", listInfo.getSendName());
            row1.put("标题", listInfo.getTitle());
            row1.put("内容", listInfo.getMsgdigest());
            row1.put("发送时间", listInfo.getCreatTime());
            switch (listInfo.getMsgLevel()) {
                case "staple":
                    row1.put("提醒级别", "正常");
                    break;
                case "importent":
                    row1.put("提醒级别", "重要");
                    break;
                case "urgency  ":
                    row1.put("提醒级别", "紧急");
                    break;
                default:
                    break;
            }

            row1.put("已读率", df.format(listInfo.getReadRate() * 100) + "%");
            List<InformationUser> acceptName = listInfo.getAcceptName();
            StringBuilder accept = new StringBuilder();
            for (InformationUser informationUser : acceptName) {
                accept.append(informationUser.getName());
                accept.append(",");
            }
            if (accept.length() > 1) {
                accept.delete(accept.length() - 1, accept.length());
            }
            row1.put("接收人", accept);
            List<InformationUser> inforUserReadById = informationUserMapper.findInforUserReadById(listInfo.getId(), 0);
            StringBuilder unread = new StringBuilder();
            for (InformationUser informationUser : inforUserReadById) {
                unread.append(informationUser.getName());
                unread.append(",");
            }
            row1.put("未读人", unread);
            rows.add(row1);
        }

        String fileName = System.currentTimeMillis() + ".xlsx";
        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(7, "调度管理统计导出");
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);

        writer.setRowHeight(-1, 30);
        writer.setColumnWidth(-1, 25);
        for (int j = 0; j < 8; j++) {
            for (int i = 2; i < rows.size() + 2; i++) {
                //设置某几行的对齐方式
                CellStyle style = writer.createCellStyle(j, i);
                // 居中对齐
                style.setAlignment(HorizontalAlignment.CENTER);
                // 垂直对齐
                style.setVerticalAlignment(VerticalAlignment.CENTER);
                //边框线类型
                style.setBorderBottom(BorderStyle.THIN);
                //下边框线颜色
                style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
                //开启自动换行
                style.setWrapText(true);
            }

        }

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        ServletOutputStream out = response.getOutputStream();
        // 关闭writer，释放内存
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);

        return fileName;

    }




}
